/*
 * Copyright (c) 2010 All Inclusive Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.allinclusive.fw.web.ajax.convertor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForward;

import com.googlecode.allinclusive.fw.web.ajax.exception.AjaxHandleException;

/**
 * <p>
 * ビジネスロジックで取得したデータをJSON形式の文字列に変換します。変換はJSON-libの仕様に基づいて行われます。
 * </p>
 * 
 */
public class JsonConvertor implements ResponseConvertor {

    /**
     * ログインスタンス
     */
    private static final Log log = LogFactory.getLog( JsonConvertor.class );
    
    /**
     * レスポンスのエンコーディング
     */
    public static final String ENCODING = "UTF-8";
    
    /**
     * ビジネスロジックで取得したデータをJSON形式の文字列に変換して、responseに格納します。
     * @param obj クライアントへのデータ
     * @param request　
     * @param response
     */
	public ActionForward convert(Object obj, HttpServletRequest request, HttpServletResponse response) {
		// JSON形式の文字列
        String output;

        // JSON形式へ変更
        if (obj instanceof Enum || obj instanceof Collection || obj instanceof Object[]) {
			JSONArray json = JSONArray.fromObject(obj);

			if (log.isDebugEnabled()) {
				log.debug("JSON:" + json.toString());
			}

			output = json.toString();
		} else {
			JSONObject json = JSONObject.fromObject(obj);
			if (log.isDebugEnabled()) {
				log.debug("JSON:" + json.toString());
			}
			output = json.toString();
		}

		//処理結果はレスポンスに書き込む
		//strutsではあるものの、直にresponseを書き込む必要がある。
		//writerを取得して流し込み、forwardはNullを返す
		PrintWriter writer;
		try {
			//直に流し込むので、HTTPヘッダも直書き
			response.setContentType("text/html; charset=" + ENCODING);
			response.addHeader("Content-Type", "text/html");
			response.addHeader("charset", ENCODING);
			response.addHeader("Cache-Control", "no-cache");
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Expires", "0");

			writer = response.getWriter();
			writer.print(output);
			//writer.close();
		} catch (IOException e) {
			throw new AjaxHandleException(e);
		}

		return null;
	}

}
